package com.heimali.sf.db;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;

import com.heimali.sf.SiFaApplication;
import com.heimali.sf.debug.Console;
import com.heimali.sf.models.Note;

public class NoteHelper extends SQLiteOpenHelper {

	protected final static String TAG = "NoteHelper";
	protected static final int DATABASE_VERSION = 1;
	protected static final String DB_NAME = "note.db";
	protected static final String TABLE_NAME = "alarm";
	protected static final int INSERT_MAX_COUNT_ONE_TIME = 300;
	protected static SQLiteDatabase database = null;
	protected static Object writeLock = new Object();
	
	private static NoteHelper dbHelper = null;
	
	public NoteHelper(Context context) {
		super(context, getDBName(), null, getDBVersion());
	}

	public NoteHelper(Context context, String name, CursorFactory factory, int version) {
		super(context, name, factory, version);
	}
	
	public static NoteHelper getInstance() {
		if (dbHelper == null) {
			dbHelper = new NoteHelper(SiFaApplication.getContext());
		}
		return dbHelper;
	}
	
	private static String getDBName() {
		return DB_NAME;
	}
	
	private static String getTable() {
		return TABLE_NAME;
	}

	private static int getDBVersion() {
		return DATABASE_VERSION;
	}
	
	private SQLiteDatabase getDatabase() {
		if (database == null) {
			database = getInstance().getWritableDatabase();
		}
		return database;
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		String scanTableSql = "create table if not exists "
				+ getTable()
				+ " (_id integer primary key autoincrement, name varchar(255), remark text, date text, time text, repeat int, ext text);";
		db.execSQL(scanTableSql);
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
	}
	
	public int insert(Note item) {
		
		synchronized (writeLock) {
			SQLiteDatabase db = getDatabase();
			try {
				String sql = "insert into " + getTable()
						+ " (name, remark, date, time, repeat, ext) values (?, ?, ?, ?, ?, ?)";
				db.beginTransaction();
				db.execSQL(sql, new Object[] {item.name, item.remark, item.date, item.time, item.repeat, ""});
				db.setTransactionSuccessful();
			} catch (SQLException e) {
				e.printStackTrace();
			} finally {
				if (db != null) {
					db.endTransaction();
				}
			}
		}
		return getLastItem().id;
	}
	
	public void delete(int id) {
		if (id <= 0) {
			return ;
		}
		
		synchronized (writeLock) {
			SQLiteDatabase db = getDatabase();
			try {
				String sql = "delete from " + getTable() + " where _id=?";
				db.beginTransaction();
				db.execSQL(sql, new Object[] {id});
				db.setTransactionSuccessful();
			} catch (SQLException e) {
				e.printStackTrace();
			} finally {
				if (db != null) {
					db.endTransaction();
				}
			}
		}
	}
	
	public List<Note> getList(String date) {
		List<Note> items = new ArrayList<Note>();
		synchronized (writeLock) {
			SQLiteDatabase db = null;
			Cursor cursor = null;
			try {
				db = getDatabase();
				cursor = db.rawQuery("select * from " + getTable() + " where date=? order by time desc", new String[]{date});
				if (cursor != null && cursor.moveToFirst()) {
					int INDEX_ID = cursor.getColumnIndexOrThrow("_id");
					int INDEX_NAME = cursor.getColumnIndexOrThrow("name");
					int INDEX_REMARK = cursor.getColumnIndexOrThrow("remark");
					int INDEX_DATE = cursor.getColumnIndexOrThrow("date");
					int INDEX_TIME = cursor.getColumnIndexOrThrow("time");
					int INDEX_REPEAT = cursor.getColumnIndexOrThrow("repeat");
//					int INDEX_ext = cursor.getColumnIndexOrThrow("ext");
					while (!cursor.isAfterLast()) {
						items.add(new Note(cursor.getString(INDEX_NAME), cursor.getString(INDEX_REMARK), cursor.getString(INDEX_DATE), cursor.getString(INDEX_TIME), cursor.getInt(INDEX_REPEAT), cursor.getInt(INDEX_ID)));
						cursor.moveToNext();
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
				Console.log("getList Exception", e.getMessage());
			} finally {
				try {
					if (cursor != null) {
						cursor.close();
						cursor = null;
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		return items;
	}
	
	public Note getItemByID(int id) {
		Note result = null;
		synchronized (writeLock) {
			SQLiteDatabase db = null;
			Cursor cursor = null;
			try {
				db = getDatabase();
				cursor = db.rawQuery("select * from " + getTable() + " where _id=?", new String[]{String.valueOf(id)});
				if (cursor != null && cursor.moveToFirst()) {
					int INDEX_ID = cursor.getColumnIndexOrThrow("_id");
					int INDEX_NAME = cursor.getColumnIndexOrThrow("name");
					int INDEX_REMARK = cursor.getColumnIndexOrThrow("remark");
					int INDEX_DATE = cursor.getColumnIndexOrThrow("date");
					int INDEX_TIME = cursor.getColumnIndexOrThrow("time");
					int INDEX_REPEAT = cursor.getColumnIndexOrThrow("repeat");
//					int INDEX_ext = cursor.getColumnIndexOrThrow("ext");
					while (!cursor.isAfterLast()) {
						result = new Note(cursor.getString(INDEX_NAME), cursor.getString(INDEX_REMARK), cursor.getString(INDEX_DATE), cursor.getString(INDEX_TIME), cursor.getInt(INDEX_REPEAT), cursor.getInt(INDEX_ID));
						cursor.moveToNext();
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
				Console.log("getList Exception", e.getMessage());
			} finally {
				try {
					if (cursor != null) {
						cursor.close();
						cursor = null;
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		return result;
	}
	
	
	public Note getLastItem() {
		Note result = null;
		synchronized (writeLock) {
			SQLiteDatabase db = null;
			Cursor cursor = null;
			try {
				db = getDatabase();
				cursor = db.rawQuery("select * from " + getTable() + " order by _id desc limit 1", null);
				if (cursor != null && cursor.moveToFirst()) {
					int INDEX_ID = cursor.getColumnIndexOrThrow("_id");
					int INDEX_NAME = cursor.getColumnIndexOrThrow("name");
					int INDEX_REMARK = cursor.getColumnIndexOrThrow("remark");
					int INDEX_DATE = cursor.getColumnIndexOrThrow("date");
					int INDEX_TIME = cursor.getColumnIndexOrThrow("time");
					int INDEX_REPEAT = cursor.getColumnIndexOrThrow("repeat");
//					int INDEX_ext = cursor.getColumnIndexOrThrow("ext");
					while (!cursor.isAfterLast()) {
						result = new Note(cursor.getString(INDEX_NAME), cursor.getString(INDEX_REMARK), cursor.getString(INDEX_DATE), cursor.getString(INDEX_TIME), cursor.getInt(INDEX_REPEAT), cursor.getInt(INDEX_ID));
						cursor.moveToNext();
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
				Console.log("getList Exception", e.getMessage());
			} finally {
				try {
					if (cursor != null) {
						cursor.close();
						cursor = null;
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		return result;
	}
	

}
